import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/http_constant.dart';
import 'package:distribution_mall_flutter/entity/user/user.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/pages/user/login/service/login_service.dart';
import 'package:distribution_mall_flutter/provider/user/login.dart';
import 'package:distribution_mall_flutter/provider/user/user_info.dart';
import 'package:distribution_mall_flutter/utils/common_widget.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/utils/debug.dart';
import 'package:distribution_mall_flutter/utils/keyboard.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:getwidget/getwidget.dart';
import 'package:pin_code_fields/pin_code_fields.dart';

@RoutePage()
class LoginVerificationPage extends ConsumerStatefulWidget {
  final String phone;

  const LoginVerificationPage({super.key, @pathParam required this.phone});

  @override
  ConsumerState createState() => _LoginVerification();
}

class _LoginVerification extends ConsumerState<LoginVerificationPage> {
  TextEditingController textEditingController = TextEditingController();
  StreamController<ErrorAnimationType>? errorController =
      StreamController<ErrorAnimationType>();
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      // sendCode();
      _focusNode.requestFocus();
    });
  }

  void sendCode() {
    ref
        .read(loginProvider.notifier)
        .getCode(ref.read(loginProvider).params)
        .then((AutoCodeEntity? data) {
      if (data == null) return;
      ref.read(loginProvider.notifier).startTime(data.sendCoolDownSecond ?? 30);
    });
  }

  @override
  Widget build(BuildContext context) {
    String code = ref.watch(loginProvider.select((value) => value.code));
    AutoCodeEntity? codeInfo =
        ref.watch(loginProvider.select((value) => value.codeInfo));
    bool loginLoading =
        ref.watch(loginProvider.select((value) => value.loginLoading));
    String? formatPhone =
        ref.watch(loginProvider.select((value) => value.formatPhone));
    Map<String, dynamic> params =
        ref.watch(loginProvider.select((value) => value.params));
    int downTime = ref.watch(loginProvider.select((value) => value.downTime));
    ref.watch(loginServiceProvider);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        leading: CommonBtnWidget.arrowBack(
          icon: Icons.arrow_back,
        ),
        title: const Text(''),
        titleSpacing: 0,
        flexibleSpace: Container(
          color: const Color.fromRGBO(245, 246, 248, 0.9),
        ),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(0.9), // 设置下划线的高度
          child: Container(
              color: ColorConstant.grey233_4, // 设置下划线的颜色
              height: 0.9 // 设置下划线的高度
              ),
        ),
      ),
      body: Container(
        padding: const EdgeInsets.symmetric(horizontal: EdgeConstant.edge218),
        decoration: const BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
              Color.fromRGBO(245, 246, 248, 0.9),
              Colors.white
              // Colors.black
              // Colors.black,
              // Colors.black,
            ],
                stops: [
              0,
              0.1
            ])),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(
              height: 79.2,
            ),
            Text(
              S.current.user_login_enter,
              style: const TextStyle(
                color: Colors.black,
                fontSize: 18.2,
                fontWeight: FontWeight.bold,
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 7.3, bottom: 3),
              child: Text(
                S.current.user_login_digit(codeInfo?.codeLength ?? ''),
                style: const TextStyle(
                    color: Colors.black, fontSize: FontConstant.f146),
              ),
            ),
            Text(
              formatPhone ?? '',
              style: const TextStyle(
                  color: Color.fromRGBO(84, 131, 191, 1),
                  fontWeight: FontWeight.bold,
                  fontSize: FontConstant.f16_4),
            ),

            (codeInfo != null && codeInfo.codeLength != null)
                ? Padding(
                    padding: const EdgeInsets.only(top: EdgeConstant.edge218),
                    child: PinCodeTextField(
                      controller: textEditingController,
                      errorAnimationController: errorController,
                      appContext: context,
                      keyboardType: TextInputType.number,
                      pastedTextStyle: const TextStyle(
                        color: Colors.black,
                        fontWeight: FontWeight.bold,
                      ),
                      length: codeInfo.codeLength!,
                      autoFocus: false,
                      autoUnfocus: true,
                      focusNode: _focusNode,
                      // obscureText: true,
                      // obscuringCharacter: '*',
                      // obscuringWidget: const FlutterLogo(
                      //   size: 24,
                      // ),
                      blinkWhenObscuring: true,
                      animationType: AnimationType.fade,
                      validator: (v) {
                        if (v!.length < 3) {
                          return "I'm from validator";
                        } else {
                          return null;
                        }
                      },
                      pinTheme: PinTheme(
                        shape: PinCodeFieldShape.box,
                        borderRadius: BorderRadius.circular(5),
                        fieldHeight: 59.2,
                        fieldWidth: 44.6,
                        activeColor: const Color.fromRGBO(241, 242, 246, 1),
                        selectedColor: ColorConstant.grey136,
                        selectedFillColor: ColorConstant.grey136,
                        inactiveColor: const Color.fromRGBO(241, 242, 246, 1),
                        inactiveFillColor:
                            const Color.fromRGBO(241, 242, 246, 1),
                        activeFillColor: Colors.white,
                      ),
                      cursorColor: Colors.black,
                      animationDuration: const Duration(milliseconds: 300),
                      enableActiveFill: true,
                      boxShadows: const [
                        BoxShadow(
                          offset: Offset(0, 1),
                          color: Colors.black12,
                          blurRadius: 10,
                        )
                      ],
                      onCompleted: (v) {
                        ref.read(loginProvider.notifier).setCode(v);
                      }, // onTap: () {
                      //   print("Pressed");
                      // },
                      onChanged: (value) {
                        ref.read(loginProvider.notifier).setCode('');
                      },
                      // beforeTextPaste: (text) {
                      //   debugPrint("Allowing to paste $text");
                      //   //if you return true then it will show the paste confirmation dialog. Otherwise if false, then nothing will happen.
                      //   //but you can show anything you want here, like your pop up saying wrong paste format or etc
                      //   return true;
                      // },
                    ),
                  )
                : const SizedBox(
                    height: 90,
                  ),
            GestureDetector(
              onTap: downTime <= 0
                  ? () {
                      sendCode();
                    }
                  : null,
              child: SizedBox(
                height: 30,
                child: downTime <= 0
                    ? Text(
                        S.current.user_login_time_resend,
                        style: const TextStyle(
                            color: Color.fromRGBO(84, 131, 191, 1)),
                      )
                    : RichText(
                        text: TextSpan(
                            style: const TextStyle(
                                color: Color.fromRGBO(134, 141, 150, 1),
                                fontSize: FontConstant.f127),
                            children: [
                            TextSpan(text: '${S.current.user_login_time} '),
                            TextSpan(
                                text: '$downTime',
                                style: const TextStyle(
                                    color: Color.fromRGBO(84, 131, 191, 1))),
                            TextSpan(text: ' ${S.current.user_login_s}')
                          ])),
              ),
            ),

            const SizedBox(
              height: 36.4,
            ),
            CommonBtnWidget.generalBtn(
                (code.isEmpty || loginLoading)
                    ? null
                    : () {
                        if (codeInfo == null) return;
                        _focusNode.unfocus();
                        ref.read(loginProvider.notifier).autoLogin({
                          'receiver': params['receiver'],
                          'receiverType': params['receiverType'],
                          'codeType': codeInfo.codeType,
                          'code': code,
                          'checkCode': codeInfo.checkCode,
                        }).then((value) async {
                          _focusNode.unfocus();
                          if (value) {
                            ref.read(loginServiceProvider).checkInviteCode();
                          }
                        });
                      },
                height: 43.7,
                radius: 7.3,
                shape: GFButtonShape.square,
                fullWidthButton: true,
                text: S.current.user_login_sign,
                textStyle: const TextStyle(
                    color: Colors.white,
                    fontSize: FontConstant.f16_4,
                    fontWeight: FontWeight.bold,
                    letterSpacing: TextConstant.letterSpacing))

            // Text(S.current.user_login_time, style: ,)
          ],
        ),
      ),
    );
  }
}
